package com.ls.lserp.modules.purchase.service;





import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.service.CrudService;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.excel.template.ExcelTemplate;
import com.ls.lserp.modules.order.dao.AuditInfoDao;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.purchase.dao.PurchaseAdvanceDao;
import com.ls.lserp.modules.purchase.entity.PurchaseAdvance;
import com.ls.lserp.modules.purchase.entity.PurchaseContract;
import com.ls.lserp.modules.sys.entity.Sequence;
import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.sys.utils.UserUtils;
@Service
@Transactional(readOnly = false)
public class PurchaseAdvanceService extends CrudService<PurchaseAdvanceDao,PurchaseAdvance>{

	//合同
	 @Autowired
	    private PurchaseAdvanceDao purchaseAdvanceDao ;

	// 审核表
		@Autowired
		    private AuditInfoDao  auditInfoDao;
	    /**
		 * 查询父项
		 * @param page
		 * @param user
		 * @return
		 */
	    public Page<PurchaseAdvance> findPurchaseAdvanceList(Page<PurchaseAdvance> page, PurchaseAdvance purchaseAdvance) {
	        // 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
	        //designOption.getSqlMap().put("dsf", dataScopeFilter(user.getCurrentUser(), "o", "a"));
	        // 设置分页参数
	    	purchaseAdvance.setPage(page);
	        // 执行分页查询
	        page.setList(purchaseAdvanceDao.findList(purchaseAdvance));
	        return page;
	    }
	    
		/**
		 * 查询一条采购预付款信息
		 * 
		 * @param user
		 * @return
		 */
	    public PurchaseAdvance getAdvance(PurchaseAdvance purchaseAdvance) {
	        
	        return purchaseAdvanceDao.get(purchaseAdvance);
	        
	    }
	    /**
		 * ID查询一条数据
		 * 
		 * @param user
		 * @return
		 */
	    public PurchaseAdvance findByID(Long id){
	    	
	    	return purchaseAdvanceDao.get(id);
	    }
	    
	    /**
		 * 新增/修改一条数据
		 * @param user
		 */
	    @Transactional(readOnly = false)
	    public void savePurchaseAdvance(PurchaseAdvance purchaseAdvance) {
	    	// 判断新建编辑
	    		//若为null 执行插入语句（新建）
	    		if (purchaseAdvance.getId()==null){
	    			// 编辑
	    			String contractNO = purchaseAdvance.getContractMaterialNO();
	    			StringBuilder conCode = new StringBuilder();
    				conCode.append("110");
    				conCode.append(contractNO);
    		        Sequence sequence=SequenceUtil.ognizationCode(conCode.toString(), "sequence_purchaseAdvance", 2);
    		        purchaseAdvance.setAdvanceNO(sequence.getReturnCode());
    		        purchaseAdvance.preInsert();
	    			purchaseAdvance.setStatus(ResourcesUtil.getConfig("audit_uncommit"));
	    			purchaseAdvanceDao.insert(purchaseAdvance);
	    				
	    		}else{
	    			// 更新数据
	    			purchaseAdvance.preInsert();
	    			purchaseAdvanceDao.update(purchaseAdvance);
	    		}			
	    }
	    
	    /**
		 * 提交一条数据
		 * @param user
		 */
	    @Transactional(readOnly = false)
	    public void commitPurchaseAdvance(PurchaseAdvance purchaseAdvance) {
	    	// 判断新建编辑
	    			// 更新数据
	    			purchaseAdvance.preInsert();
	    			purchaseAdvance.setStatus(ResourcesUtil.getConfig("reserver_meterial_wait_accept"));
	    			purchaseAdvanceDao.commitUpdate(purchaseAdvance);
	    }
	    /**
		 * 删除一条数据
		 * @param user
		 */
	    @Transactional(readOnly = false)
	    public void deletePurchaseAdvance(PurchaseAdvance purchaseAdvance) {
	    	// 判断新建编辑
	    			// 更新数据
	    			purchaseAdvance.preInsert();
	    			purchaseAdvanceDao.delete(purchaseAdvance);
	    }
	    
	    /**
	     * @Title: findAuditList
	     * @Description: 查询所有履历
	     * @param @param auditInfo
	     * @param @return
	     * @return List<AuditInfo> 
	     * @throws
	     */
	   public AuditInfo findAuditInfo(AuditInfo auditInfo) {
		   AuditInfo audit = new AuditInfo();
		   audit.setAuditList(auditInfoDao.findAllList(auditInfo));
		   audit.setAuditStatus(auditInfoDao.findAuditAcceptCount(auditInfo));
	       // 执行查询
	       return audit;
	   }
	   /**
	    * @Title: getAuditResult
	    * @Description: 审核结果
	    * @param @param auditInfo
	    * @param @return
	    * @return 审核结果通过数
	    * @throws
	    */
	  
	  public long getAuditResult(AuditInfo auditInfo) {
		   
	      return auditInfoDao.findAuditAcceptCount(auditInfo);
	  }
	  
	  /**
		  * @Title: saveAudit
		  * @Description: 保存履历信息
		  * @param @param auditInfo
		  * @return void 
		  * @throws
		  */
		@Transactional(readOnly = false)
		public void saveAuditInfo(AuditInfo auditInfo,boolean isUpdateStatus) {
			
			 // 插入履历表
		     auditInfo.preInsert();
		     auditInfo.setAuditDate(new Date());
		     auditInfo.setAuditUserId(UserUtils.getUser().getId());
	         // 新建版本号赋值1
		     auditInfo.setVersion(1L);
		     auditInfoDao.insert(auditInfo);
		     
		     auditInfo.preUpdate();
		     if (auditInfo.getAuditResult()==0) {
		    	 auditInfo.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_no"));
			}else if (auditInfo.getAuditResult()==1) {
				auditInfo.setContractAuditStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
			}
		     
		     purchaseAdvanceDao.updateStatus(auditInfo);
		     
		}
		/**
	     * 导出预付款信息
	     *
	     * @throws IOException
	     */
	    public ExcelTemplate exportOrderMateriel(PurchaseContract purchaseContract,PurchaseAdvance purchaseAdvance, String tempFilePath) throws IOException {
	        // 返回值
	        ExcelTemplate handle = new ExcelTemplate();
	        // 输出预付款信息
	        printpurchaseAdvanceInfoTemp(tempFilePath, purchaseAdvance, handle);
	        // 物料详细信息
	        printpurchaseMaterialInfoTemp(tempFilePath, purchaseContract.getMaterialList(), handle);
	        return handle;
	    }
	    
	    private void printpurchaseAdvanceInfoTemp(String tempFilePath, PurchaseAdvance purchaseAdvance, ExcelTemplate handle) throws IOException {
	    	List<String> dataCellDeclare = new ArrayList<String>();
	        // 变量值
	        Map<String, Object> dataMapResult = new HashMap<String, Object>();
	        // 格式化数字
	        NumberFormat num = NumberFormat.getInstance();

	        // 创建人员
	        dataCellDeclare.add("firstName");
	        dataMapResult.put("firstName", purchaseAdvance.getCreateBy().getFirstName());
	        // 签订日期(核料信息)
	        dataCellDeclare.add("appDate");
	        if ("".equals(purchaseAdvance.getAppDate()) || purchaseAdvance.getAppDate() == null) {
	        	dataMapResult.put("appDate", "");
	        } else {
	        	dataMapResult.put("appDate", DateUtils.formatDate(purchaseAdvance.getAppDate(), "yyyy-MM-dd") );
	        }
	        // 供货商
	        dataCellDeclare.add("ognizationName");
	        dataMapResult.put("ognizationName", purchaseAdvance.getOgnizationName());
	        // 开户银行
	        dataCellDeclare.add("bankName");
	        dataMapResult.put("bankName", purchaseAdvance.getBankName());
	        // 银行账户
	        dataCellDeclare.add("bankAccountNo");
	        dataMapResult.put("bankAccountNo", purchaseAdvance.getBankAccountNo());
	        
	        // 预付款金额 
	        dataCellDeclare.add("advanceAmount");
	        if ("".equals(purchaseAdvance.getAdvanceAmount()) || purchaseAdvance.getAdvanceAmount() == null) {
	        	dataMapResult.put("advanceAmount", purchaseAdvance.getAdvanceAmount());
	        } else {
	        	dataMapResult.put("advanceAmount", num.format(purchaseAdvance.getAdvanceAmount()));
	        }
			// 预付款比例
			dataCellDeclare.add("advanceRate");
			if ("".equals(purchaseAdvance.getAdvanceRate()) || purchaseAdvance.getAdvanceRate() == null) {
				dataMapResult.put("advanceRate", purchaseAdvance.getAdvanceRate()+"%");
			} else {
				dataMapResult.put("advanceRate", num.format(purchaseAdvance.getAdvanceRate())+"%");
			}
			// 付款期限
			dataCellDeclare.add("advanceDueDate");
			if ("".equals(purchaseAdvance.getAdvanceDueDate()) || purchaseAdvance.getAdvanceDueDate() == null) {
				dataMapResult.put("advanceDueDate", "");
			} else {
				dataMapResult.put("advanceDueDate", DateUtils.formatDate(purchaseAdvance.getAdvanceDueDate(), "yyyy-MM-dd"));
			}
	        // 向excel表输出
	        handle.writeData(tempFilePath, dataCellDeclare, dataMapResult, 0);
	    }
	    
	    private void printpurchaseMaterialInfoTemp(String tempFilePath, List<PurchaseContract> materialList, ExcelTemplate handle) throws IOException {
	    	// 变量声明
	        List<String> dataCellDeclare = new ArrayList<String>();
	        // 变量值集合
	        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
	        dataCellDeclare.add("purchaseUnitPrice");
	        dataCellDeclare.add("purchaseReserveQuantity");
	        dataCellDeclare.add("purchaseAllCost");
	        dataCellDeclare.add("materialCode");
	        
	        // 结果
	        Map<String, Object> map;
	        // 临时接收变量
	        PurchaseContract tempBean;
	        // 格式化数字
	        NumberFormat num = NumberFormat.getInstance();
	    	for (int i = 0; i < materialList.size(); i++) {
	    		map = new HashMap<String, Object>();
    			tempBean = materialList.get(i);
    			// 采购单价
    			if ("".equals(tempBean.getPurchaseUnitPrice()) || tempBean.getPurchaseUnitPrice() == null) {
    				map.put("purchaseUnitPrice", tempBean.getPurchaseUnitPrice());
    			} else {
    				map.put("purchaseUnitPrice", num.format(tempBean.getPurchaseUnitPrice()));
    			}
    			// 采购数量
    			if ("".equals(tempBean.getPurchaseReserveQuantity()) || tempBean.getPurchaseReserveQuantity() == null) {
    				map.put("purchaseReserveQuantity", tempBean.getPurchaseReserveQuantity());
    			} else {
    				map.put("purchaseReserveQuantity", num.format(tempBean.getPurchaseReserveQuantity()));
    			}
    			// 采购金额
    			map.put("purchaseAllCost", tempBean.getPurchaseAllCost());
    			// 物料编码
    			if ("".equals(tempBean.getMaterialNameCN()) || tempBean.getMaterialNameCN() == null) {
    				map.put("materialCode", tempBean.getMaterialCode());
    			} else {
    				map.put("materialCode", tempBean.getMaterialCode()+"/"+tempBean.getMaterialNameCN());
    			}
	    		dataList.add(map);
	        }
	    	// 向excel表输出
	        handle.writeListData(tempFilePath, dataCellDeclare, dataList, 0);
	    }
	        
}
